<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="card-title">
        <span>提现</span>
      </div>
      <!-- 已经添加的银行的盒子 -->
      <!-- 添加银行卡的按钮 -->
      <div v-if="!bankCardList.length" class="new-car-box">
        <!-- 按此按钮实现路由跳转 -->
        <router-link :to="{ path: '/account/card' }">
          <el-button type="success" icon="el-icon-circle-plus-outline"
            >请先添加银行卡</el-button
          >
        </router-link>
      </div>
      <!-- 判断如果数据为空的话，就不显示 -->
      <div v-else class="bankCard-list">
        <template>
          <!-- 以添加的银行卡容器 -->
          <span style="margin-left: 18px">请选择收款银行卡</span>
          <div class="card-box">
            <div
              v-for="(item, index) in bankCardList"
              :key="index"
              style="position: relative"
              @click="selected(index)"
              :class="{ selectedstyle: index === extractForm.selectedIndex }"
            >
              <div class="card-info">
                <span>{{ item.bankName }}</span>
                <span>{{ item.cardNum }}</span>
              </div>
            </div>
          </div>
          <el-divider></el-divider>
          <div class="bottom">
            <el-form
              :model="extractForm"
              :rules="rules"
              ref="extractForm"
              label-width="80px"
              class="demo-extractForm"
            >
              <el-form-item prop="selectedIndex" class="selected-item">
              </el-form-item>
              <el-form-item label="可取金额:">
                <span>{{ this.accountInfo.balance }} 元</span>
              </el-form-item>

              <el-form-item label="提取金额:">
                <el-input-number
                  :controls="false"
                  v-model="extractForm.amount"
                  :min="1"
                  :max="100000"
                ></el-input-number>
              </el-form-item>

              <el-form-item prop="pass">
                <div class="identify-box" @click="makeCode">
                  <SIdentify :identifyCode="identifycode"></SIdentify>
                </div>
              </el-form-item>

              <el-form-item label="验证码:" prop="verifycode">
                <el-input v-model="extractForm.verifycode"></el-input>
              </el-form-item>

              <el-form-item label="支付密码:" prop="payPwd" show-password>
                <el-input v-model="extractForm.payPwd"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitForm('extractForm')"
                  >提现</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </template>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import { authRealNameAndPWS } from "@/utils/auth";
import SIdentify from "@/components/Identify/SIdentify.vue";
export default {
  // 注册组件才能在页面上使用
  components: {
    SIdentify,
  },
  data() {
    // 验证码的校验
    var validateverifycode = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入验证码"));
      } else if (value != this.identifycode) {
        console.log(value, this.identifycode);
        callback(new Error("验证码错误"));
      } else {
        callback();
      }
    };
    return {
      extractForm: {
        // 金额充值
        amount: "",
        // 验证码
        verifycode: "",
        // 当前选择银行索引
        selectedIndex: "",
        // 支付密码
        payPwd: "",
        // 银行卡ID
        card_id: "",
      },
      // 校验规则
      rules: {
        selectedIndex: [
          { required: true, trigger: "change", message: "请选择银行" },
        ],
        verifycode: [{ validator: validateverifycode, trigger: "blur" }],
        payPwd: { required: true, trigger: "blur", message: "请输入支付密码" },
      },
      // 生成随机数
      identifycode: "",
      identifycodes: "0123456789",
    };
  },
  methods: {
    ...mapActions({
      // 获取银行卡信息
      getBankCard: "card/getBankCard",
      // 提现
      extract: "assetManage/extract",
      // 获取用户账户信息
      getInfo: "user/getInfo",
    }),
    // 点击银行图片
    selected(index) {
      if (index === this.extractForm.selectedIndex) {
        // 假如传进来的索引和已经记录的索引相同，就取消记录的索引
        this.extractForm.selectedIndex = ""; // 就是如果你点击了2次相同的银行的话，就会取消选择
      } else {
        // 如果和记录的索引不相同，就记录当前传入的索引
        this.extractForm.selectedIndex = index;
        this.extractForm.card_id = this.bankCardList[index].cardId;
        this.$refs.extractForm.clearValidate("selectedIndex"); // 清除校验
      }
    },
    readomNum(max) {
      // Math.floor向下取整数，Math.random()生成0到1之间的随机数，包含0，但不包含1
      return Math.floor(Math.random() * max);
    },
    // 生成验证码图片（4位随机数字）
    makeCode() {
      this.identifycode = "";
      for (let index = 0; index < 4; index++) {
        this.identifycode +=
          this.identifycodes[this.readomNum(this.identifycodes.length)];
      }
      console.log("验证码的四位数是", this.identifycode);
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(this.extractForm);
          this.extract(this.extractForm).then((res) => {
            this.$message({
              message: "提现成功",
              type: "success",
            });
            this.onCancel('extractForm')
            // 提现成功就刷新验证码
            this.makeCode();
            // 提现成功就重新获取用户信息
            this.getInfo();
          });
        } else {
          alert("error");
          return false;
        }
      });
    },
    // 重置表单
    onCancel(formname) {
      // restFields对整个表单进行进行重置
      this.$refs[formname].resetFields();
      // 重置金额
      this.extractForm.amount = 1
    },
  },
  // 页面创建的时候应该做什么
  mounted() {
    // 拦截器（第二个传的是用哪个来判断是否拦截）
    authRealNameAndPWS(this,'payPwdStatus')
    this.makeCode();
    console.log("在创建页面的时候的四位数是", this.identifycode);
    this.getBankCard();
  },
  computed: {
    // 银行卡列表
    ...mapGetters(["name", "bankCardList", "accountInfo"]),
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  .card-title {
    font-size: 22px;
  }
  .card-box {
    display: flex;
    flex-wrap: wrap;
    .card-info {
      width: 200px;
      height: 120px;
      background-color: #cedfff;
      border-radius: 5%; // 圆角
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin: 1px 12px;
    }
  }
  .el-input {
    max-width: 200px;
    padding: 0 12px 0;
  }
  .selectedstyle {
    .card-info {
      border: 2px solid rgb(28, 104, 167);
    }
  }
}
</style>
